// pages/biz-manage/os.js
// pages/i/order-boot.js
const auth = require('../../utils/auth.js')
const bizPayService = require('../../services/bizPay.js')
const bizOrderService = require('../../services/bizOrder.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        activeIndex: 0,
        isLoggedIn: false,
        userInfo: null,
        loginReady: false,

        // 支付记录相关
        payRecords: [],
        loading: false,
        hasMore: true,
        currentPage: 1,
        pageSize: 10,
        payRecordVisible: false,

        // 支付记录详情相关
        payRecordDetail: null,
        detailLoading: false,
        detailError: null,
        currentRecordId: null,

        // 消费订单相关
        consumptionOrders: [],
        consumptionLoading: false,
        consumptionHasMore: true,
        consumptionCurrentPage: 1,
        consumptionPageSize: 10,

        // 核销码相关
        ticketList: [],
        ticketLoading: false,
        ticketHasMore: true,
        ticketCurrentPage: 1,
        ticketPageSize: 10,

        // 日期选择器相关
        showDatePicker: false,
        currentDate: new Date().getTime(),
        minDate: new Date(2020, 0, 1).getTime(),
        maxDate: new Date(2030, 11, 31).getTime(),
        selectedDateType: '', // 'start' 或 'end'
        startDate: '',
        endDate: '',
        phone: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.checkLoginStatus()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (this.data.loginReady == false) {
            this.checkLoginStatus()

            if (this.data.activeIndex == 1) {
                this.loadConsumptionOrders()
            } else if (this.data.activeIndex == 0) {
                this.loadPayRecords()
            } else if (this.data.activeIndex == 2) {
                this.loadTicketList()
            }
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        if (this.data.activeIndex == 1) {
            this.refreshConsumptionOrders().finally(() => {
                wx.stopPullDownRefresh()
            })
        } else if (this.data.activeIndex == 0) {
            this.refreshPayRecords().finally(() => {
                wx.stopPullDownRefresh()
            })
        } else if (this.data.activeIndex == 2) {
            this.refreshTicketList().finally(() => {
                wx.stopPullDownRefresh()
            })
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.activeIndex == 1 && this.data.consumptionHasMore && !this.data.consumptionLoading) {
            this.loadMoreConsumptionOrders()
        } else if (this.data.activeIndex == 0 && this.data.hasMore && !this.data.loading) {
            this.loadMorePayRecords()
        } else if (this.data.activeIndex == 2 && this.data.ticketHasMore && !this.data.ticketLoading) {
            this.loadMoreTicketList()
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    /**
     * 菜单点击事件
     */
    handleMenuClick(e) {
        const index = e.currentTarget.dataset.index;
        this.setData({
            activeIndex: index
        });
        
        // 如果切换到消费订单菜单，加载消费订单
        if (index == 1 && this.data.loginReady) {
            this.loadConsumptionOrders()
        }
        // 如果切换到支付记录菜单，加载支付记录
        else if (index == 0 && this.data.loginReady) {
            this.loadPayRecords()
        }
        else if (index == 2 && this.data.loginReady) {
            this.loadTicketList()
        }
    },

    /**
       * 检查登录状态
       */
    async checkLoginStatus() {
        try {
            const loginStatus = await auth.checkLoginStatus()
            console.log('检查登录状态:', loginStatus)

            // 如果未登录或未绑定手机号，直接跳转到登录页面
            if (!loginStatus.isLoggedIn || !auth.isValidUserInfo(loginStatus.userInfo)) {
                wx.navigateTo({
                    url: '/pages/index/login'
                })
                return
            }

            this.setData({
                isLoggedIn: loginStatus.isLoggedIn,
                userInfo: loginStatus.userInfo,
                loginReady: true
            })

            this.loadPayRecords()

        } catch (error) {
            console.error('检查登录状态失败:', error)
            // 检查失败时也跳转到登录页面
            wx.navigateTo({
                url: '/pages/index/login'
            })
        }
    },

    /**
     * 加载支付记录列表
     */
    async loadPayRecords() {
        if (this.data.loading) return

        this.setData({ loading: true })

        try {
            const result = await bizPayService.recordsByBiz({
                phone: this.data.phone,
                start_date: this.data.startDate,
                end_date: this.data.endDate,
                page: 1,
                limit: this.data.pageSize
            })

            console.log(result);

            if (result.success) {
                const { records, total, has_more } = result.data
                
                this.setData({
                    payRecords: records || [],
                    hasMore: has_more,
                    currentPage: 1
                })

            } else {
                wx.showToast({
                    title: result.message,
                    icon: 'none'
                })
            }
        } catch (error) {
            
            wx.showToast({
                title: '获取支付记录失败',
                icon: 'none'
            })
        } finally {
            this.setData({ loading: false })
        }
    },

    /**
     * 加载更多支付记录
     */
    async loadMorePayRecords() {
        if (this.data.loading || !this.data.hasMore) return

        this.setData({ loading: true })

        try {
            const nextPage = this.data.currentPage + 1
            const result = await bizPayService.recordsByBiz({
                phone: this.data.phone,
                start_date: this.data.startDate,
                end_date: this.data.endDate,
                page: nextPage,
                limit: this.data.pageSize
            })

            if (result.success) {
                const { records, has_more } = result.data
                
                if (records && records.length > 0) {
                    this.setData({
                        payRecords: [...this.data.payRecords, ...records],
                        hasMore: has_more,
                        currentPage: nextPage
                    })
                } else {
                    this.setData({
                        hasMore: false
                    })
                }
            } else {
                wx.showToast({
                    title: result.message || '加载更多失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载更多支付记录失败:', error)
            wx.showToast({
                title: '加载更多失败',
                icon: 'none'
            })
        } finally {
            this.setData({ loading: false })
        }
    },

    /**
     * 刷新支付记录
     */
    async refreshPayRecords() {
        this.setData({
            payRecords: [],
            hasMore: true,
            currentPage: 1
        })
        
        await this.loadPayRecords()
    },

    // 商家发起退款
    handleRefund(e) {
        const id = e.currentTarget.dataset.id
        console.log(id);

        wx.showModal({
            title: '提示',
            content: '确定要发起退款吗？发起后会在1-5分钟之内完成退款。',
            success: (res) => {
                if (res.confirm) {
                    this.refund(id)
                }
            }
        })
    },

    // 商家发起退款
    async refund(id) {  
        try {
            const result = await bizPayService.refundByBiz({
                id: id
            })

            if (result.success) {
                wx.showToast({
                    title: result.message,
                    icon: 'success'
                })

                this.refreshPayRecords()
            } else {
                wx.showToast({
                    title: result.message,
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('退款失败:', error)
        }
    },

    /**
     * 加载消费订单列表
     */
    async loadConsumptionOrders() {
        if (this.data.consumptionLoading) return

        this.setData({ consumptionLoading: true })

        try {
            const result = await bizOrderService.getOrderListByBiz(1, this.data.consumptionPageSize)

            if (result.success) {
                const { list, total, has_more } = result.data
                
                this.setData({
                    consumptionOrders: list || [],
                    consumptionHasMore: has_more,
                    consumptionCurrentPage: 1
                })

                console.log('消费订单列表:', list)
            } else {
                wx.showToast({
                    title: result.message || '获取消费订单失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载消费订单失败:', error)
            wx.showToast({
                title: '获取消费订单失败',
                icon: 'none'
            })
        } finally {
            this.setData({ consumptionLoading: false })
        }
    },

    /**
     * 加载更多消费订单
     */
    async loadMoreConsumptionOrders() {
        if (this.data.consumptionLoading || !this.data.consumptionHasMore) return

        this.setData({ consumptionLoading: true })

        try {
            const nextPage = this.data.consumptionCurrentPage + 1
            const result = await bizOrderService.getOrderListByBiz(nextPage, this.data.consumptionPageSize)

            if (result.success) {
                const { list, has_more } = result.data
                
                if (list && list.length > 0) {
                    this.setData({
                        consumptionOrders: [...this.data.consumptionOrders, ...list],
                        consumptionHasMore: has_more,
                        consumptionCurrentPage: nextPage
                    })
                } else {
                    this.setData({
                        consumptionHasMore: false
                    })
                }
            } else {
                wx.showToast({
                    title: result.message || '加载更多失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载更多消费订单失败:', error)
            wx.showToast({
                title: '加载更多失败',
                icon: 'none'
            })
        } finally {
            this.setData({ consumptionLoading: false })
        }
    },

    /**
     * 刷新消费订单
     */
    async refreshConsumptionOrders() {
        this.setData({
            consumptionOrders: [],
            consumptionHasMore: true,
            consumptionCurrentPage: 1
        })
        
        await this.loadConsumptionOrders()
    },

    // 加载核销码列表
    async loadTicketList() {
        if (this.data.ticketLoading) return

        this.setData({ ticketLoading: true })

        try {
            const result = await bizOrderService.getTicketListByBiz(1, this.data.ticketPageSize)

            if (result.success) {
                const { list, total, has_more } = result.data
                
                this.setData({
                    ticketList: list || [],
                    ticketHasMore: has_more,
                    ticketCurrentPage: 1
                })
            }
            else {
                wx.showToast({
                    title: result.message || '获取核销码失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('加载核销码列表失败:', error)
            wx.showToast({
                title: '获取核销码失败',
                icon: 'none'
            })
        } finally {
            this.setData({ ticketLoading: false })
        }
    },

    // 加载更多核销码
    async loadMoreTicketList() {
        if (this.data.ticketLoading || !this.data.ticketHasMore) return

        this.setData({ ticketLoading: true })

        try {
            const nextPage = this.data.ticketCurrentPage + 1
            const result = await bizOrderService.getTicketListByBiz(nextPage, this.data.ticketPageSize)
        } catch (error) {
            console.error('加载更多核销码失败:', error)
            wx.showToast({
                title: '加载更多失败',
                icon: 'none'
            })
        } finally {
            this.setData({ ticketLoading: false })
        }
    },

    // 刷新核销码列表
    async refreshTicketList() {
        this.setData({
            ticketList: [],
            ticketHasMore: true,
            ticketCurrentPage: 1
        })
    },

    // 打开日期选择器
    openDatePicker(e) {
        const type = e.currentTarget.dataset.type; // 'start' 或 'end'
        this.setData({ 
            showDatePicker: true,
            selectedDateType: type
        });
    },

    // 关闭日期选择器
    onCloseDatePicker() {
        this.setData({ showDatePicker: false });
    },

    // 确认日期选择
    onConfirmDatePicker(e) {
        const { detail } = e;
        const selectedDate = new Date(detail);
        const dateString = this.formatDate(selectedDate);
        
        if (this.data.selectedDateType === 'start') {
            this.setData({ 
                startDate: dateString,
                showDatePicker: false 
            });
        } else if (this.data.selectedDateType === 'end') {
            this.setData({ 
                endDate: dateString,
                showDatePicker: false 
            });
        }
        
        console.log('选择的日期:', dateString);
    },

    // 格式化日期
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    },

    // 搜索支付记录
    doSearchPayRecords() {
        this.loadPayRecords();
    }
})